package com.atgouwu.mall.order.service.impl;

import com.alibaba.fastjson.TypeReference;
import com.atgouwu.mall.common.exception.NoStockException;
import com.atgouwu.mall.common.utils.Query;
import com.atgouwu.mall.common.utils.R;
import com.atgouwu.mall.common.vo.MemberResponseVo;
import com.atgouwu.mall.order.constant.PayConstant;
import com.atgouwu.mall.order.entity.OrderItemEntity;
import com.atgouwu.mall.order.entity.PaymentInfoEntity;
import com.atgouwu.mall.order.enume.OrderStatusEnum;
import com.atgouwu.mall.order.feign.CartFeignService;
import com.atgouwu.mall.order.feign.MemberFeignService;
import com.atgouwu.mall.order.feign.ProductFeignService;
import com.atgouwu.mall.order.feign.WmsFeignService;
import com.atgouwu.mall.order.interceptor.MyHandlerInterceptor;
import com.atgouwu.mall.order.service.OrderItemService;
import com.atgouwu.mall.order.service.PaymentInfoService;
import com.atgouwu.mall.order.to.OrderCreateTo;
import com.atgouwu.mall.order.to.SpuInfoVo;
import com.atgouwu.mall.order.vo.*;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atgouwu.mall.common.utils.PageUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.atgouwu.mall.order.dao.OrderDao;
import com.atgouwu.mall.order.entity.OrderEntity;
import com.atgouwu.mall.order.service.OrderService;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;

import static com.atgouwu.mall.common.constant.CartConstant.CART_PREFIX;
import static com.atgouwu.mall.order.constant.OrderConstant.USER_ORDER_TOKEN_PREFIX;

@Service("orderService")
public class OrderServiceImpl extends ServiceImpl<OrderDao, OrderEntity> implements OrderService {

    @Autowired
    private MemberFeignService memberFeignService;
    @Autowired
    private ThreadPoolExecutor threadPoolExecutor;
    @Autowired
    private CartFeignService cartFeignService;
    @Autowired
    private WmsFeignService wmsFeignService;
    @Autowired
    private StringRedisTemplate redisTemplate;
    private ThreadLocal<OrderSubmitVo> confirmVoThreadLocal = new ThreadLocal<>();
    @Autowired
    private ProductFeignService productFeignService;
    @Autowired
    private OrderItemService orderItemService;
    @Autowired
    private RabbitTemplate rabbitTemplate;
    @Autowired
    private PaymentInfoService paymentInfoService;
//    @Autowired
//    private BestPayService bestPayService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<OrderEntity> page = this.page(
                new Page<>(Long.valueOf(String.valueOf(params.get("page"))), Long.valueOf(String.valueOf(params.get("size")))),
                new QueryWrapper<OrderEntity>()
        );
        return new PageUtils(page.getRecords(), (int) page.getTotal(), (int) page.getSize(), (int) page.getCurrent());
    }

    //获取待提交订单
    @Override
    public OrderConfirmVo confirmOrder() throws ExecutionException, InterruptedException {
        OrderConfirmVo confirmVo = new OrderConfirmVo();
        MemberResponseVo memberResponseVo = MyHandlerInterceptor.loginUser.get(); //获取当前用户
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes(); //(获取主线程请求头,解决异步时feign远程调用丢失请求头)
        CompletableFuture<Void> addressFuture = CompletableFuture.runAsync(() -> { //(开启第一个异步任务)
            RequestContextHolder.setRequestAttributes(requestAttributes); //(每个线程都共享主请求头,解决异步时feign远程调用丢失请求头)
            List<MemberAddressVo> address = memberFeignService.getAddress(memberResponseVo.getId()); //获取地址列表(远程调用member会员服务)
            confirmVo.setMemberAddressVos(address);
        }, threadPoolExecutor);
        CompletableFuture<Void> cartInfoFuture = CompletableFuture.runAsync(() -> { //(开启第二个异步任务)
            RequestContextHolder.setRequestAttributes(requestAttributes); //(每个线程都共享主请求头,解决异步时feign远程调用丢失请求头)
            List<OrderItemVo> currentCartItems = cartFeignService.getCurrentCartItems(memberResponseVo.getToken()); //获取购物车所有选中购物项(远程调用cart购物车服务)
            confirmVo.setItems(currentCartItems);
        }, threadPoolExecutor).thenRunAsync(() -> {
            List<OrderItemVo> items = confirmVo.getItems();
            List<Long> skuIds = items.stream().map((itemVo -> itemVo.getSkuId())).collect(Collectors.toList()); //获取全部商品id
            R skuHasStock = wmsFeignService.getSkuHasStock(skuIds); //获取商品库存信息(远程调用ware仓储服务)
            List<SkuStockVo> skuStockVos = skuHasStock.getData("data", new TypeReference<List<SkuStockVo>>() {
            });
            if (skuStockVos != null && skuStockVos.size() > 0) {
                Map<Long, Boolean> skuHasStockMap = skuStockVos.stream().collect(Collectors.toMap(SkuStockVo::getSkuId, SkuStockVo::getHasStock)); //将skuStockVos集合转为map
                confirmVo.setStocks(skuHasStockMap);
            }
        }, threadPoolExecutor);
        Integer integration = memberResponseVo.getIntegration(); //查询用户积分
        confirmVo.setIntegration(integration); //价格数据自动计算
        String token = UUID.randomUUID().toString().replace("-", ""); //防重令牌(防止表单重复提交)
        redisTemplate.opsForValue().set(USER_ORDER_TOKEN_PREFIX + memberResponseVo.getId(), token, 30, TimeUnit.MINUTES); //为用户设置token存在redis,三十分钟过期时间
        confirmVo.setOrderToken(token); //token也返给页面
        CompletableFuture.allOf(addressFuture, cartInfoFuture).get();
        return confirmVo;
    }

    @Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRED, isolation = Isolation.DEFAULT)
    //@GlobalTransactional(rollbackFor = Exception.class)
    @Override
    public SubmitOrderResponseVo submitOrder(OrderSubmitVo vo) {
        confirmVoThreadLocal.set(vo);
        SubmitOrderResponseVo responseVo = new SubmitOrderResponseVo();
        MemberResponseVo memberResponseVo = MyHandlerInterceptor.loginUser.get(); //获取当前用户
        responseVo.setCode(0); //默认状态码0成功,1失败
        String orderToken = vo.getOrderToken(); //验证令牌是否合法(令牌对比和删除必须保证原子性)
        String script = "if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del', KEYS[1]) else return 0 end";
        Long result = redisTemplate.execute(new DefaultRedisScript<Long>(script, Long.class), Arrays.asList(USER_ORDER_TOKEN_PREFIX + memberResponseVo.getId()), orderToken); //通过lure脚本原子验证令牌和删除令牌
        if (result == 0L) { //令牌验证失败
            responseVo.setCode(1);
            return responseVo;
        } else { //令牌验证成功
            OrderCreateTo order = createOrder(vo.getToken()); //创建订单,订单项等信息
            BigDecimal payAmount = order.getOrder().getPayAmount(); //验证价格
            BigDecimal payPrice = vo.getPayPrice();
            if (Math.abs(payAmount.subtract(payPrice).doubleValue()) < 1000.01) { //金额对比
                saveOrder(order); //保存订单和订单项
                WareSkuLockVo lockVo = new WareSkuLockVo(); //库存锁定(有异常回滚订单)
                lockVo.setOrderSn(order.getOrder().getOrderSn()); //订单号
                List<OrderItemVo> orderItemVos = order.getOrderItems().stream().map((item) -> { //所有订单项信息(skuId,skuNum,skuName)
                    OrderItemVo orderItemVo = new OrderItemVo();
                    orderItemVo.setSkuId(item.getSkuId());
                    orderItemVo.setCount(item.getSkuQuantity());
                    orderItemVo.setTitle(item.getSkuName());
                    return orderItemVo;
                }).collect(Collectors.toList());
                lockVo.setLocks(orderItemVos);
                //seata:解决网络超时,其它远程调用失败,导致事务回滚不一致, mq:seata加锁并行化,效率低,不推荐用,高并发可发消息给库存服务
                R r = wmsFeignService.orderLockStock(lockVo); //锁定库存(远程调用ware仓储服务)
                if (r.getCode() == 200) { //锁成功
                    responseVo.setOrder(order.getOrder());
                    //rabbitTemplate.convertAndSend("order-event-exchange","order.create.order",order.getOrder()); //订单创建成功,发送消息给MQ
                    redisTemplate.delete(CART_PREFIX + memberResponseVo.getId()); //删除购物车
                    return responseVo;
                } else { //锁失败
                    String msg = (String) r.get("msg");
                    throw new NoStockException(msg);
                }
            } else {
                responseVo.setCode(2);
                return responseVo;
            }
        }
    }

    //创建订单,订单项等信息
    private OrderCreateTo createOrder(String token) {
        OrderCreateTo createTo = new OrderCreateTo();
        String orderSn = IdWorker.getTimeId(); //生成订单号
        OrderEntity orderEntity = builderOrder(orderSn); //设置:用户,订单号,收货地址,运费,收货人信息
        List<OrderItemEntity> orderItemEntities = builderOrderItems(orderSn, token); //获取所有订单项
        computePrice(orderEntity, orderItemEntities); //验价(重新计算价格,积分等信息)
        createTo.setOrder(orderEntity);
        createTo.setOrderItems(orderItemEntities);
        return createTo;
    }

    //设置:用户,订单号,收货地址,运费,收货人信息
    private OrderEntity builderOrder(String orderSn) {
        MemberResponseVo memberResponseVo = MyHandlerInterceptor.loginUser.get(); //获取当前用户
        OrderEntity orderEntity = new OrderEntity();
        orderEntity.setMemberId(memberResponseVo.getId());
        orderEntity.setOrderSn(orderSn);
        orderEntity.setMemberUsername(memberResponseVo.getUsername());
        OrderSubmitVo orderSubmitVo = confirmVoThreadLocal.get();
        R fareAddressVo = wmsFeignService.getFare(orderSubmitVo.getAddrId()); //获取收货地址和运费(远程调用ware仓储服务)
        FareVo fareResp = fareAddressVo.getData("data", new TypeReference<FareVo>() {
        });
        BigDecimal fare = fareResp.getFare(); //获取到运费信息
        orderEntity.setFreightAmount(fare);
        MemberAddressVo address = fareResp.getAddress(); //获取到收货地址信息
        orderEntity.setReceiverName(address.getName()); //设置收货人信息
        orderEntity.setReceiverPhone(address.getPhone());
        orderEntity.setReceiverPostCode(address.getPostCode());
        orderEntity.setReceiverProvince(address.getProvince());
        orderEntity.setReceiverCity(address.getCity());
        orderEntity.setReceiverRegion(address.getRegion());
        orderEntity.setReceiverDetailAddress(address.getDetailAddress());
        orderEntity.setStatus(OrderStatusEnum.CREATE_NEW.getCode()); //设置订单相关的状态信息
        orderEntity.setAutoConfirmDay(7);
        orderEntity.setConfirmStatus(0);
        return orderEntity;
    }

    //获取所有订单项
    public List<OrderItemEntity> builderOrderItems(String orderSn, String token) {
        List<OrderItemEntity> orderItemEntityList = new ArrayList<>();
        List<OrderItemVo> currentCartItems = cartFeignService.getCurrentCartItems(token); //获取订单项,确定每个购物项价格(远程调用cart购物车服务)
        if (currentCartItems != null && currentCartItems.size() > 0) {
            orderItemEntityList = currentCartItems.stream().map((items) -> {
                OrderItemEntity orderItemEntity = builderOrderItem(items); //构建订单项数据
                orderItemEntity.setOrderSn(orderSn);
                return orderItemEntity;
            }).collect(Collectors.toList());
        }
        return orderItemEntityList;
    }

    //构建订单项数据
    private OrderItemEntity builderOrderItem(OrderItemVo items) {
        OrderItemEntity orderItemEntity = new OrderItemEntity();
        Long skuId = items.getSkuId(); //商品的spu信息
        R spuInfo = productFeignService.getSpuInfoBySkuId(skuId); //获取spu信息(远程调用product商品服务)
        SpuInfoVo spuInfoData = spuInfo.getData("data", new TypeReference<SpuInfoVo>() {
        });
        orderItemEntity.setSpuId(spuInfoData.getId()); //spu信息
        orderItemEntity.setSpuName(spuInfoData.getSpuName());
        orderItemEntity.setSpuBrand(spuInfoData.getBrandName());
        orderItemEntity.setCategoryId(spuInfoData.getCatalogId());
        orderItemEntity.setSkuId(skuId); //sku商品信息
        orderItemEntity.setSkuName(items.getTitle());
        orderItemEntity.setSkuPic(items.getImage());
        orderItemEntity.setSkuPrice(items.getPrice());
        orderItemEntity.setSkuQuantity(items.getCount());
        String skuAttrValues = StringUtils.collectionToDelimitedString(items.getSkuAttrValues(), ";"); //用StringUtils.collectionToDelimitedString将list集合转为String
        orderItemEntity.setSkuAttrsVals(skuAttrValues);
        orderItemEntity.setGiftGrowth(items.getPrice().multiply(new BigDecimal(items.getCount())).intValue()); //商品的优惠信息
        orderItemEntity.setGiftIntegration(items.getPrice().multiply(new BigDecimal(items.getCount())).intValue()); //商品的积分信息
        orderItemEntity.setPromotionAmount(BigDecimal.ZERO); //订单项价格信息
        orderItemEntity.setCouponAmount(BigDecimal.ZERO);
        orderItemEntity.setIntegrationAmount(BigDecimal.ZERO);
        BigDecimal origin = orderItemEntity.getSkuPrice().multiply(new BigDecimal(orderItemEntity.getSkuQuantity().toString())); //原来价格
        BigDecimal subtract = origin.subtract(orderItemEntity.getCouponAmount()).subtract(orderItemEntity.getPromotionAmount()).subtract(orderItemEntity.getIntegrationAmount()); //原价减去优惠价得到最终价格
        orderItemEntity.setRealAmount(subtract); //实际金额
        return orderItemEntity;
    }

    //验价(重新计算价格,积分等信息)
    private void computePrice(OrderEntity orderEntity, List<OrderItemEntity> orderItemEntities) {
        BigDecimal total = new BigDecimal("0.0"); //总价
        BigDecimal coupon = new BigDecimal("0.0"); //优惠价
        BigDecimal intergration = new BigDecimal("0.0");
        BigDecimal promotion = new BigDecimal("0.0");
        Integer integrationTotal = 0; //积分,成长值
        Integer growthTotal = 0;
        for (OrderItemEntity orderItem : orderItemEntities) {
            coupon = coupon.add(orderItem.getCouponAmount()); //优惠价格
            promotion = promotion.add(orderItem.getPromotionAmount()); //打折价格
            intergration = intergration.add(orderItem.getIntegrationAmount()); //积分价格
            total = total.add(orderItem.getRealAmount()); //订单总额,叠加每个订单项的总额信息
            integrationTotal += orderItem.getGiftIntegration(); //积分信息和成长值信息
            growthTotal += orderItem.getGiftGrowth();
        }
        orderEntity.setTotalAmount(total); //订单价格
        orderEntity.setPayAmount(total.add(orderEntity.getFreightAmount())); //设置应付总额(总额+运费)
        orderEntity.setCouponAmount(coupon);
        orderEntity.setPromotionAmount(promotion);
        orderEntity.setIntegrationAmount(intergration);
        orderEntity.setIntegration(integrationTotal); //设置积分成长值信息
        orderEntity.setGrowth(growthTotal);
        orderEntity.setDeleteStatus(0); //设置删除状态(0未删除,1已删除)
    }

    //保存订单和订单项
    private void saveOrder(OrderCreateTo orderCreateTo) {
        OrderEntity order = orderCreateTo.getOrder(); //获取订单信息
        order.setModifyTime(new Date());
        order.setCreateTime(new Date());
        baseMapper.insert(order); //保存订单
        List<OrderItemEntity> orderItems = orderCreateTo.getOrderItems(); //获取订单项信息
        orderItemService.saveBatch(orderItems); //批量保存订单项数据
    }

    //根据订单号获取订单
    @Override
    public PayVo getOrderPay(String orderSn) {
        PayVo payVo = new PayVo();
        OrderEntity orderInfo = baseMapper.selectOne(new QueryWrapper<OrderEntity>().eq("order_sn", orderSn));
        BigDecimal payAmount = orderInfo.getPayAmount().setScale(2, BigDecimal.ROUND_UP);
        payVo.setTotal_amount(payAmount.toString()); //保留两位小数点,向上取值
        payVo.setOut_trade_no(orderInfo.getOrderSn());
        List<OrderItemEntity> orderItemInfo = orderItemService.list(new QueryWrapper<OrderItemEntity>().eq("order_sn", orderSn)); //查询订单项数据
        OrderItemEntity orderItemEntity = orderItemInfo.get(0);
        payVo.setBody(orderItemEntity.getSkuAttrsVals());
        payVo.setSubject(orderItemEntity.getSkuName());
        return payVo;
    }

    //分页获取已提交订单
    @Override
    public PageUtils queryPageWithItem(Map<String, Object> params) {
        MemberResponseVo memberResponseVo = MyHandlerInterceptor.loginUser.get();
        IPage<OrderEntity> page = this.page( //分页获取订单
                new Query<OrderEntity>().getPage(params),
                new QueryWrapper<OrderEntity>().eq("member_id", memberResponseVo.getId()).orderByDesc("create_time")
        );
        List<OrderEntity> orderEntityList = page.getRecords().stream().map(order -> {
            List<OrderItemEntity> orderItemEntities = orderItemService.list(new QueryWrapper<OrderItemEntity>().eq("order_sn", order.getOrderSn())); //根据订单号获取订单项
            order.setOrderItemEntityList(orderItemEntities);
            order.setCreateTimes(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(order.getCreateTime()));
            switch (order.getStatus()) {
                case 0:
                    order.setStatuss("待付款");
                    break;
                case 1:
                    order.setStatuss("代发货");
                    break;
                case 2:
                    order.setStatuss("已发货");
                    break;
                case 3:
                    order.setStatuss("已完成");
                    break;
                case 4:
                    order.setStatuss("已关闭");
                    break;
                default:
                    order.setStatuss("无效订单");
                    break;
            }
            return order;
        }).collect(Collectors.toList());
        page.setRecords(orderEntityList);
        return new PageUtils(page);
    }

    //修改订单状态
    @Transactional(rollbackFor = Exception.class)
    @Override
    public String handlePayResult(PayAsyncVo asyncVo) {
        PaymentInfoEntity paymentInfo = new PaymentInfoEntity();
        paymentInfo.setOrderSn(asyncVo.getOut_trade_no());
        paymentInfo.setAlipayTradeNo(asyncVo.getTrade_no());
        paymentInfo.setTotalAmount(new BigDecimal(asyncVo.getBuyer_pay_amount()));
        paymentInfo.setSubject(asyncVo.getBody());
        paymentInfo.setPaymentStatus(asyncVo.getTrade_status());
        paymentInfo.setCreateTime(new Date());
        paymentInfo.setCallbackTime(asyncVo.getNotify_time());
        paymentInfoService.save(paymentInfo); //保存交易流水信息
        String tradeStatus = asyncVo.getTrade_status(); //交易状态
        if (tradeStatus.equals("TRADE_SUCCESS") || tradeStatus.equals("TRADE_FINISHED")) {
            String orderSn = asyncVo.getOut_trade_no(); //获取订单号
            baseMapper.updateOrderStatus(orderSn, OrderStatusEnum.PAYED.getCode(), PayConstant.ALIPAY); //修改订单状态
        }
        return "success";
    }

    @Override
    public String asyncNotify(String notifyData) {
//        //签名效验
//        PayResponse payResponse = bestPayService.asyncNotify(notifyData);
//        log.info("payResponse={}",payResponse);
//        //2.金额效验（从数据库查订单）
//        OrderEntity orderEntity = this.getOrderByOrderSn(payResponse.getOrderId());
//        //如果查询出来的数据是null的话
//        //比较严重(正常情况下是不会发生的)发出告警：钉钉、短信
//        if (orderEntity == null) {
//            //TODO 发出告警，钉钉，短信
//            throw new RuntimeException("通过订单编号查询出来的结果是null");
//        }
//        //判断订单状态状态是否为已支付或者是已取消,如果不是订单状态不是已支付状态
//        Integer status = orderEntity.getStatus();
//        if (status.equals(OrderStatusEnum.PAYED.getCode()) || status.equals(OrderStatusEnum.CANCLED.getCode())) {
//            throw new RuntimeException("该订单已失效,orderNo=" + payResponse.getOrderId());
//        }
//        /*//判断金额是否一致,Double类型比较大小，精度问题不好控制
//        if (orderEntity.getPayAmount().compareTo(BigDecimal.valueOf(payResponse.getOrderAmount())) != 0) {
//            //TODO 告警
//            throw new RuntimeException("异步通知中的金额和数据库里的不一致,orderNo=" + payResponse.getOrderId());
//        }*/
//        //3.修改订单支付状态
//        //支付成功状态
//        String orderSn = orderEntity.getOrderSn();
//        this.updateOrderStatus(orderSn,OrderStatusEnum.PAYED.getCode(),PayConstant.WXPAY);
        //4.告诉微信不要再重复通知了
        return "<xml>\n" +
                "  <return_code><![CDATA[SUCCESS]]></return_code>\n" +
                "  <return_msg><![CDATA[OK]]></return_msg>\n" +
                "</xml>";
    }

}